<?php

namespace app\shop\controller;

use think\Controller;

class Order extends Controller
{
    protected $busid;
    protected $Business;

    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->BusinessModel = model('Business.Business');
        $this->RegionModel = model('Region');
        $this->AddressModel = model('Business.Address');
        $this->OrderModel = model('Product.Order');
        $this->OrderProductModel = model('Product.OrderProduct');
        $this->ProductModel = model('Product.Product');
        $this->CartModel = model('Product.Cart');
        $this->RecordModel = model('Business.Record');
        $this->CouponReceiveModel = model('Coupon.Receive');
        $this->CommissionModel = model('Business.Commission');
        $this->ExpressqueryModel = model('Expressquery');
        $this->BackModel = model('Depot.Back');
        $this->BackProductModel = model('Depot.BackProduct');

        $this->busid = $this->request->param('busid', 0, 'trim');

        $this->Business = $this->BusinessModel->find($this->busid);

        if (!$this->Business) {
            $this->error('用户不存在');
            exit;
        }
    }

    //下单
    public function add()
    {
        if ($this->request->isPost()) {
            $businessaddrid = $this->request->param('businessaddrid', 0, 'trim');
            $cartids = $this->request->param('cartids', '', 'trim');
            $couponid = $this->request->param('couponid', 0, 'trim');
            $pay =  $this->request->param('pay', 'money', 'trim');
            $remark = $this->request->param('remark', '', 'trim');
            $amount = $this->request->param('amount', 0, 'trim');
            $isDirectlyBuy = $this->request->param('isDirectlyBuy', 0, 'trim');

            $address = $this->AddressModel->find($businessaddrid);
            if (!$address) {
                $this->error('收货地址不存在');
                exit;
            }

            $cartlist = $this->CartModel->with('product')->where('cart.id', 'IN', $cartids)->select();

            if (!$cartlist) {
                $this->error('购物车商品不存在');
                exit;
            }

            //查询是否有选择优惠券
            $coupon = $this->CouponReceiveModel->with('coupon')->where(['receive.status' => '1'])->find($couponid);


            // 余额支付
            if ($pay === 'money') {

                /*
                    订单表  新增
                    订单商品表  批量新增
                    用户表  更新
                    用户消费记录表  新增
                    购物车表    删除
                    产品表  库存批量更新
                    优惠券  更新

                    开启事务
                */
                $this->OrderModel->startTrans();
                $this->OrderProductModel->startTrans();
                $this->BusinessModel->startTrans();
                $this->RecordModel->startTrans();
                $this->ProductModel->startTrans();
                $this->CartModel->startTrans();
                $this->CouponReceiveModel->startTrans();
                $this->CommissionModel->startTrans();

                $code = build_code('SP');

                $OrderData = [
                    'code' => $code,
                    'busid' => $this->busid,
                    'businessaddrid' => $businessaddrid,
                    'amount' => $amount,
                    'remark' => $remark,
                    'status' => '1',
                    'pay' => $pay
                ];

                // 表示有使用优惠券
                if ($coupon) {
                    $OrderData['couponid'] = $couponid;
                }

                // 校验器， 订单表
                $OrderStatus = $this->OrderModel->save($OrderData);

                if ($OrderStatus === false) {
                    $this->error($this->OrderModel->getError());
                }

                //产品表
                $ProductData = [];

                // 订单产品表
                $OrderProductData = [];

                foreach ($cartlist as $item) {
                    $stock = bcsub($item['product']['stock'], $item['nums']);

                    if ($stock < 0) {
                        $this->error("{$item['product']['name']}库存不足");
                        exit;
                    }

                    $ProductData[] = [
                        'id' => $item['proid'],
                        'stock' => $stock
                    ];

                    $OrderProductData[] = [
                        'orderid' => $this->OrderModel->id,
                        'busid' => $this->busid,
                        'proid' => $item['proid'],
                        'pronum' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                        'attrs' => $item['attrs']
                    ];
                }

                // 订单产品表，循环校验器
                $OrderProductStatus = $this->OrderProductModel->saveAll($OrderProductData);

                if ($OrderProductStatus === false) {
                    $this->OrderModel->rollback();
                    $this->error($this->OrderProductModel->getError());
                }

                // 剩余余额
                $money = bcsub($this->Business['money'], $amount, 2);

                $BusinessData = [
                    'id' => $this->Business['id'],
                    'money' => $money
                ];

                $validate = [
                    [
                        'money' => ['number', 'egt:0'],
                    ],
                    [
                        'money.number'  => '余额必须是数字类型',
                        'money.egt'      => '余额不足请先充值',
                    ]
                ];

                // 用户表
                $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

                if ($BusinessStatus === false) {
                    $this->OrderModel->rollback();
                    $this->OrderProductModel->rollback();
                    $this->error($this->BusinessModel->getError());
                    exit;
                }

                $RecordData = [
                    'total' => $amount,
                    'busid' => $this->Business['id'],
                    'content' => "商城订单号：$code ---消费的金额：$amount 元"
                ];

                // 消费记录表
                $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
                if ($RecordStatus === false) {
                    $this->OrderModel->rollback();
                    $this->OrderProductModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->error($this->RecordModel->getError());
                    exit;
                }

                // 产品表
                $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

                if ($ProductStatus === false) {
                    $this->OrderModel->rollback();
                    $this->OrderProductModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->error($this->ProductModel->getError());
                    exit;
                }

                // 购物车
                $CartStatus = $this->CartModel->destroy($cartids);
                // 判断是否是立即购买
                if ($isDirectlyBuy == 1) {
                    $this->CartModel->commit();
                }
                if ($CartStatus === false) {
                    $this->OrderModel->rollback();
                    $this->OrderProductModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->ProductModel->rollback();
                    $this->error($this->CartModel->getError());
                    exit;
                }
                //如果有选择优惠券那么就要更新优惠券使用状态
                if ($coupon) {
                    $CouponReceiveData = [
                        'id' => $couponid,
                        'status' => '0'
                    ];

                    $CouponReceiveStatus =  $this->CouponReceiveModel->isUpdate(true)->save($CouponReceiveData);
                    if ($CouponReceiveStatus === false) {
                        $this->OrderModel->rollback();
                        $this->OrderProductModel->rollback();
                        $this->BusinessModel->rollback();
                        $this->RecordModel->rollback();
                        $this->ProductModel->rollback();
                        $this->CartModel->rollback();
                        $this->error($this->CouponReceiveModel->getError());
                        exit;
                    }
                }

                // 推荐人佣金
                // 获取推荐人信息
                $parentid = isset($this->Business['parentid']) ? trim($this->Business['parentid']) : 0;
                $parent = $this->BusinessModel->find($parentid);

                if ($parent) {
                    // 组装用户佣金表记录
                    $CommissionData = [
                        'orderid' => $this->OrderModel->id,   //获取插入最后一条的自增ID
                        'busid' => $this->Business['id'],
                        'parentid' => $parentid,
                        'amount' => bcmul($amount, config('site.AmountRate'), 2),
                        'type' => 'product',
                        'status' => '0'
                    ];

                    // 新增用户佣金表记录
                    $CommissionStatus = $this->CommissionModel->save($CommissionData);
                    if ($CommissionStatus === false) {
                        $this->OrderModel->rollback();
                        $this->OrderProductModel->rollback();
                        $this->BusinessModel->rollback();
                        $this->RecordModel->rollback();
                        $this->ProductModel->rollback();
                        $this->CartModel->rollback();
                        $this->error($this->CommissionModel->getError());
                        exit;
                    }
                }

                // 提交事务
                if ($OrderStatus === false || $OrderProductStatus === false || $BusinessStatus === false || $RecordStatus === FALSE || $CartStatus === FALSE || $ProductStatus === FALSE) {
                    $this->OrderModel->rollback();
                    $this->OrderProductModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->CartModel->rollback();
                    $this->ProductModel->rollback();
                    $this->CouponReceiveModel->rollback();
                    $this->CommissionModel->rollback();
                    $this->error('下单失败');
                } else {
                    $this->OrderModel->commit();
                    $this->OrderProductModel->commit();
                    $this->BusinessModel->commit();
                    $this->RecordModel->commit();
                    $this->CartModel->commit();
                    $this->ProductModel->commit();
                    $this->CouponReceiveModel->commit();
                    $this->CommissionModel->commit();
                    $this->success('下单成功');
                }
            } else {
            }
        }
    }

    // 列表
    public function index()
    {
        if ($this->request->isPost()) {
            $status  = $this->request->param('status', '', 'trim');

            $where = [
                'busid' => $this->busid
            ];

            if ($status != 0) {
                if ($status > 0) {
                    $where['status'] = $status;
                } else {
                    $where['status'] = ['IN', ['-1', '-2', '-3', '-4', '-5']];
                }
            }

            $data = $this->OrderModel->where($where)->order('createtime desc')->select();

            foreach ($data as $item) {
                $info = $this->OrderProductModel->with('product')->where(['orderid' => $item['id']])->find();

                $item['info'] = $info;
            }

            $this->success('', '', $data);
        }
    }


    // 详情
    public function info()
    {
        if ($this->request->isPost()) {
            $orderid  = $this->request->param('orderid', 0, 'trim');
            $orderproid = $this->request->param('orderproid', 0, 'trim');

            $orderinfo = $this->OrderModel->with('address')->find($orderid);

            if (!$orderinfo) {
                $this->error('订单不存在');
                exit;
            }

            $where = ['orderid' => $orderid,];

            if ($orderproid > 0) {
                $where['order_product.id'] = $orderproid;
            }

            $info = $this->OrderProductModel->with('product')->where($where)->select();

            // 退货商家地址
            $orderinfo['refund'] = [
                'company' => config('site.card_company') ?? '',
                'mobile' => config('site.card_mobile') ?? '',
                'address' => config('site.card_address') ?? '',
            ];

            // 物流信息
            $express = [];

            $backinfo = $this->BackModel->where(['ordercode' => $orderinfo['code']])->find();

            if ($backinfo) {
                $expresscode = isset($backinfo['expresscode']) ? $backinfo['expresscode'] : '';

                if ($expresscode) {
                    if (cache($expresscode)) {
                        // 获取缓存
                        $express = cache($expresscode);
                    } else {

                        $res = query_express($expresscode);

                        if ($res['code'] == 0) {
                            $this->error($res['msg']);
                            exit;
                        }

                        // 设置物流信息缓存
                        cache($expresscode, $res['data']);

                        $express = $res['data'];
                    }
                }
            }

            $backinfo['express'] = $express;

            $orderinfo['backinfo'] = $backinfo;

            $orderinfo['info'] = $info;

            $this->success('', '', $orderinfo);
        }
    }

    // 确认收货
    public function receipt()
    {
        if ($this->request->isPost()) {
            $orderid  = $this->request->param('orderid', 0, 'trim');

            $orderinfo = $this->OrderModel->find($orderid);

            if (!$orderinfo) {
                $this->error('订单不存在');
                exit;
            }

            $result = $this->OrderModel->where('id', $orderid)->update(['status' => '3']);

            if ($result === false) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('操作成功');
                exit;
            }
        }
    }

    // 评价
    public function rate()
    {
        if ($this->request->isPost()) {
            $orderid  = $this->request->param('orderid', 0, 'trim');
            $orderproid = $this->request->param('orderproid', 0, 'trim');
            $rate = $this->request->param('rate', 0, 'trim');
            $comment = $this->request->param('comment', '', 'trim');

            $orderinfo = $this->OrderModel->find($orderid);

            if (!$orderinfo) {
                $this->error('订单不存在');
                exit;
            }

            $orderproductinfo = $this->OrderProductModel->find($orderproid);

            if (!$orderproductinfo) {
                $this->error('订单商品不存在');
                exit;
            }

            //判断是否是最后一个商品评价
            $rate_status = false;

            // 查询当前订单所有商品未评价
            $orderproductlist = $this->OrderProductModel->where(['orderid' => $orderid, 'rate' => null])->column('id');

            if (in_array($orderproid, $orderproductlist) && count($orderproductlist) == 1) {
                $rate_status = true;
            }

            // 最后一个商品评价，需要改订单表状态和订单产品表评价信息
            if ($rate_status) {
                $this->OrderModel->startTrans();
                $this->OrderProductModel->startTrans();

                $OrderStatus = $this->OrderModel->where('id', $orderid)->update(['status' => '4']);

                if ($OrderStatus === false) {
                    $this->error($this->OrderModel->getError());
                    exit;
                }

                $data = [
                    'id' => $orderproid,
                    'comment' => $comment,
                    'rate' => $rate,
                    'comtime' => time(),
                ];

                // 判断是否有评价图片
                if (isset($_FILES[$orderproid]) && $_FILES[$orderproid]['size'] > 0) {
                    $res = uploads($orderproid);

                    if ($res['code'] == 0) {
                        $this->error($res['msg']);
                        exit;
                    }

                    $data['thumbs'] = $res['data'];
                }

                $OrderProductStatus = $this->OrderProductModel->isUpdate(true)->save($data);

                if ($OrderProductStatus === false) {
                    $this->OrderModel->rollback();
                    $this->error($this->OrderProductModel->getError());
                    exit;
                }

                if ($OrderStatus === false || $OrderProductStatus === false) {
                    $this->OrderModel->rollback();
                    $this->OrderProductModel->rollback();
                    $this->error('评价失败');
                } else {
                    $this->OrderModel->commit();
                    $this->OrderProductModel->commit();
                    $this->success('评价成功');
                }
            }
            // 其中商品评价
            else {
                $data = [
                    'id' => $orderproid,
                    'comment' => $comment,
                    'rate' => $rate,
                    'comtime' => time(),
                ];

                // 判断是否有评价图片
                if (isset($_FILES[$orderproid]) && $_FILES[$orderproid]['size'] > 0) {
                    $res = uploads($orderproid);

                    if ($res['code'] == 0) {
                        $this->error($res['msg']);
                        exit;
                    }

                    $data['thumbs'] = $res['data'];
                }

                $result = $this->OrderProductModel->isUpdate(true)->save($data);

                if ($result === false) {
                    $this->error($this->OrderProductModel->getError());
                    exit;
                } else {
                    $this->success('评价成功');
                    exit;
                }
            }
        }
    }

    // 物流详情
    public function express()
    {
        if ($this->request->isPost()) {
            $orderid  = $this->request->param('orderid', 0, 'trim');

            $orderinfo = $this->OrderModel->find($orderid);

            if (!$orderinfo) {
                $this->error('订单不存在');
                exit;
            }

            $express = [];

            $expresscode = isset($orderinfo['expresscode']) ? $orderinfo['expresscode'] : '';

            if ($expresscode) {
                if (cache($expresscode)) {
                    // 获取缓存
                    $express = cache($expresscode);

                    $this->success('', '', $express);
                } else {
                    $res = query_express($expresscode);

                    if ($res['code'] == 0) {
                        $this->error($res['msg']);
                        exit;
                    }

                    // 设置物流信息缓存
                    cache($expresscode, $res['data']);

                    $express = $res['data'];

                    $this->success('', '', $express);
                }
            } else {
                $this->error('暂无物流信息');
            }
        }
    }

    // 申请退货
    public function refund()
    {
        if ($this->request->isPost()) {
            $orderid  = $this->request->param('orderid', 0, 'trim');
            $status = $this->request->param('status', '', 'trim');
            $business_reason = $this->request->param('business_reason', '', 'trim');

            $orderinfo = $this->OrderModel->find($orderid);

            if (!$orderinfo) {
                $this->error('订单不存在');
                exit;
            }

            $data = [
                'id' => $orderid,
                'status' => $status,
                'business_reason' => $business_reason
            ];

            $result = $this->OrderModel->where('id', $orderid)->update($data);

            if ($result === false) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('申请成功，待商家审核');
                exit;
            }
        }
    }

    // 物流公司
    public function logistics()
    {
        if ($this->request->isPost()) {
            $data = $this->ExpressqueryModel->field('id as value,name as text')->select();

            $this->success('', '', $data);
        }
    }
  
    // 退货商品
    public function refundgoods()
    {
        if ($this->request->isPost())
        {
            $orderid = $this->request->param('orderid', 0, 'trim');
            $addressid = $this->request->param('addressid', 0, 'trim');
            $expressid = $this->request->param('expressid', 0, 'trim');
            $expresscode = $this->request->param('expresscode', '', 'trim');

            $orderinfo = $this->OrderModel->find($orderid);

            if (!$orderinfo)
            {
                $this->error('订单不存在');
                exit;
            }

            $addressinfo = $this->AddressModel->find($addressid);

            if (!$addressinfo)
            {
                $this->error('退货地址不存在');
                exit;
            }

            $expressinfo = $this->ExpressqueryModel->find($expressid);

            if (!$expressinfo)
            {
                $this->error('物流公司不存在');
            }

            $orderproductlist = $this->OrderProductModel->with('product')->where('orderid', $orderid)->select();

            if (!$orderproductlist)
            {
                $this->error('订单商品不存在');
            }

            $backinfo = $this->BackModel->where(['ordercode' => $orderinfo['code']])->find();

            if ($backinfo)
            {
                $this->error('已退货，无需要重复退货');
            }

            //生成退货单
            $this->BackModel->startTrans();
            $this->BackProductModel->startTrans();

            $BackData = [
                'code' => build_code('BP'),
                'ordercode' => $orderinfo['code'],
                'busid' => $this->busid,
                'contact' => $addressinfo['consignee'],
                'phone' => $addressinfo['mobile'],
                'address' => $addressinfo['address'],
                'province' => $addressinfo['province'],
                'city' => $addressinfo['city'],
                'district' => $addressinfo['district'],
                'amount' => $orderinfo['amount'],
                'expressid' => $expressid,
                'expresscode' => $expresscode,
                'status' => '1'
            ];

            // 校验器
            $BackStatus = $this->BackModel->save($BackData);

            if ($BackStatus === false)
            {
                $this->error($this->BackModel->getError());
                exit;
            }

            $BackProductData = [];

            foreach($orderproductlist as $item)
            {
                $BackProductData[] = [
                    'backid' => $this->BackModel->id,
                    'proid' => $item['proid'],
                    'nums' => $item['pronum'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];
            }

            $BackProductStatus = $this->BackProductModel->saveAll($BackProductData);

            if ($BackProductStatus === false)
            {
                $this->BackModel->rollback();
                $this->error($this->BackProductModel->getError());
                exit;
            }

            if($BackProductStatus === false || $BackStatus === false)
            {
                $this->BackModel->rollback();
                $this->BackProductModel->rollback();
                $this->error('退货失败');
            }
            else
            {
                $this->BackModel->commit();
                $this->BackProductModel->commit();
                $this->success('退货成功');
            }
        }
    }
}
